package com.bing.habit.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.bing.habit.entity.User;
import com.bing.habit.exception.UserLoginException;
import com.bing.habit.model.WxLoginInfo;
import com.bing.habit.model.result.Result;
import com.bing.habit.model.result.ResultFactory;
import com.bing.habit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * 用户登录操作
 */
@RestController
@Slf4j
public class LoginController {

    @Autowired
    UserService userService;
    @Autowired
    RestTemplate restTemplate;
    //小程序 appId
    @Value("${wx.user.appId}")
    private String appId;
    //小程序 appSecret
    @Value("${wx.user.secret}")
    private String secret;

    /**
     * 微信小程序登录接口
     * @param requestUser 用户信息
     * @return 返回
     */
    @PostMapping(value = "/wx/api/login")
    public Result wxLogin(@RequestBody WxLoginInfo requestUser) {
        String code = requestUser.getCode();
        //System.out.println("code===>"+code);
        log.debug("code===>" + code);

        String openid = null;
        String sessionKey = null;
        User user = null;
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId +
                            "&secret=" + secret +
                            "&js_code=" + code +
                            "&grant_type=authorization_code";
            //进行登录凭证校验
            String jsonData = this.restTemplate.getForObject(url, String.class);

            //json对象转Map
            JSONObject jsonObject = JSONObject.parseObject(jsonData);
            Map<String, Object> map = (Map<String, Object>) jsonObject;

            openid = map.get("openid").toString();//获取openid
            sessionKey = map.get("session_key").toString();//获取sessionKey
            //根据openid判断用户是否曾经登录过
            user = userService.findByOpenid(openid);
        } catch (Exception e) {
            throw new UserLoginException("用户登录过程异常");
        }

        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setSessionKey(sessionKey);
            userService.addOrUpdata(user);

        } else {
            System.out.println("用户已存在");
        }

        return ResultFactory.buildSuccessResult(user.getId());

    }
}
